package com.wyd.utils;


import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public final class MD5 {

    private static final String UTF8 = "UTF-8";

    public static String encode(String content) {
        return encode(content, UTF8);
    }

    /**
     * Md5加密  返回值全部大写
     *
     * @param messge
     * @param encoding
     * @return md5 result
     */
    public static String encode(String messge, String encoding) {
        try {
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(messge.getBytes(encoding));// 使用指定的字节更新摘要
            byte[] md = mdInst.digest();// 获得密文
            return ByteUtil.byteArrToHexStr(md).toLowerCase();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * Md5加密  返回byte数组
     *
     * @param messge
     * @param encoding
     * @return md5 result
     */
    public static byte[] encodeToByte(String messge, String encoding) {
        try {
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            if (StringUtils.isNotEmpty(encoding)) {
                mdInst.update(messge.getBytes(encoding));// 使用指定的字节更新摘要
            } else {
                mdInst.update(messge.getBytes());
            }
            return mdInst.digest();// 获得密文
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public static String MD5Encode2HexStr(String message, String charsetname) {
        try {
            return ByteUtil.byteArrToHexStr(encodeToByte(message, charsetname)).toUpperCase();
        } catch (Exception e) {
            log.error("MD5Encode2HexStr error:{}", e.getMessage(), e);
            return null;
        }

    }

    public static String md5(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            log.error("NoSuchAlgorithmException caught!");
//            System.exit(-1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (messageDigest == null) {
            return null;
        }
        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(
                        Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return md5StrBuff.toString();
    }
}
